package com.aiou.security.app.authentication;

import com.aiou.security.validate.code.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zyb
 */
@Component
@Slf4j
public class DefaultAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    public static ThreadLocal<String> errorMessage = ThreadLocal.withInitial(() -> null);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登入失败");

        String message = "用户名或密码错误！";
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        if (exception instanceof ValidateCodeException) {
            message = exception.getMessage();
        }
        response.sendError(403, message);

        errorMessage.set(message);
    }

}
